package com.lry.basic.jvm.asm.transform_class.demo13;

import java.lang.reflect.Field;

import aj.org.objectweb.asm.ClassReader;
import aj.org.objectweb.asm.ClassVisitor;
import aj.org.objectweb.asm.ClassWriter;
import com.lry.basic.jvm.asm.utils.FileUtils;

import static aj.org.objectweb.asm.Opcodes.*;

public class Test {

    public static void main(String[] args) throws Exception {

        test();

        String relativePath = "com/lry/basic/jvm/asm/transform_class/demo13/HelloWorld.class";
        String filePath = FileUtils.getFilePath(relativePath);
        byte[] b = FileUtils.readBytes(filePath);

        ClassReader cr = new ClassReader(b);

        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);

        ClassVisitor cv = new MethodEmptyBodyVisitor(ASM4,cw,"login","(Ljava/lang/String;Ljava/lang/String;)Z");

        cr.accept(cv,ClassReader.SKIP_DEBUG|ClassReader.SKIP_FRAMES);

        byte[] b2 = cw.toByteArray();

        FileUtils.writeBytes(filePath, b2);

        //用自己的类加载器从磁盘加载class
        MyClassLoader mcl = new MyClassLoader();
        mcl.defineClass("com.lry.basic.jvm.asm.transform_class.demo13.HelloWorld",b2);
        Class clazz = mcl.loadClass("com.lry.basic.jvm.asm.transform_class.demo13.HelloWorld");
        System.out.println(clazz.getDeclaredMethod("login", String.class, String.class).invoke(clazz.newInstance(),
                "lry", "ler"));

        //之前系统加载器加载过HelloWorld，所以此时还是用的缓存，没有从磁盘及时更新
        test();

    }

    private static void test() throws Exception {

        HelloWorld helloWorld = new HelloWorld();

        System.out.println(helloWorld.login("lry", "lry"));

    }

}
